package mailsystem.audio;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;

public class AudioRecorder implements Runnable {
	private TargetDataLine line;
	private AudioFileFormat.Type targetType;
	private AudioInputStream audioInputStream;
	private File outputFile;
	private AudioFormat audioFormat;
	private DataLine.Info info;

	public void prepareRecord(String filename) {
		audioFormat = new AudioFormat(
				AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F,
				false);
		info = new DataLine.Info(TargetDataLine.class, audioFormat);
		
		line = null;
		
		try {
			line = (TargetDataLine) AudioSystem.getLine(info);
			line.open(audioFormat);
		} catch (LineUnavailableException e) {
			e.printStackTrace();
			System.exit(1);
		}

		targetType = AudioFileFormat.Type.WAVE;		
		audioInputStream = new AudioInputStream(line);
		outputFile = new File(filename);
	}

	public void stopRecording() {
		line.stop();
		line.close();
	}
	
	public String getNewAudioFileName()
	{
		File folder = new File("audio");
        
        return "audio/" + (folder.list().length + 1) + ".wav";
	}

	@Override
	public void run() {
		try {
			line.start();
			AudioSystem.write(audioInputStream, targetType, outputFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
